<?php

namespace App\Http\Controllers\Logic;

use App\Http\Controllers\Controller;
use App\Model\OAMatter;
use App\Model\OAOrders;
use App\Model\OASupplier;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class MatterLogic extends Controller
{
    //添加报销
    public function addMatter($params)
    {
        try {
            DB::beginTransaction();
            $order_id = $params['order_id'];
            $order = OAOrders::query()->where('id',$order_id)->first();
            if(is_null($order)) throw new \Exception('订单需求不存在');
            $now = time();
            $start = strtotime($order->start_at);
            $end = strtotime($order->end_at);

            if($now < $start) throw new \Exception('竞价时间还未开始,请稍后重试');

            if($now > $end){
                $order->status = 2;
                $order->save();
                throw new \Exception('竞价时间已结束,请下次再来');
            }

            $count = OAMatter::query()->where('order_id',$order_id)->where('supplier_id',$params['uid'])->count('id');
            if(!$order_id && $count >= $order->rows) throw new \Exception('最多只能竞价'. $order->rows.'次');
            $files = $params['files'] ?? [];
            if($files){
                $temp = [];
                foreach ($files as $k => $file){
                    if(in_array($file['fileName'],$temp)){
                        unset($files[$k]);
                    }else{
                        array_push($temp,$file['fileName']);
                    }
                }
            }
            $matter_data = [
                'order_id'     => $params['order_id'],
                'supplier_id'   => $params['uid'],
                'type'          => $params['type'] ?? '询竞价',
                'method'        => $params['method'] ?? '邀请',
                'pay_method'    => $params['pay_method'] ?? '微信',
                'currency'      => $params['currency'] ?? 'RMB',
                'av'            => $params['av'] ?? '',
                'material'      => $params['material'] ?? '',
                'third_party'   => $params['third_party'] ?? '',
                'money'         => $params['money'] ?? 0,
                'tax'           => $params['tax'] ?? 0,
                'unit'          => $params['unit'] ?? '项',
                'files'         => json_encode($files,JSON_UNESCAPED_UNICODE),
                'desc'          => $params['desc'],
                'add_time'      => date('Y-m-d H:i:s'),
                'unit_cost'    => $params['unit_cost'] ?? 0
            ];
            //dd($matter_data);
            if(isset($params['id']) && !empty($params['id'])){
                unset($matter_data['orders_id'],$matter_data['supplier_id']);
                OAMatter::query()->where('id',$params['id'])->update($matter_data);
                $m_id = $params['id'];
            }else{
                $m_id = OAMatter::query()->insertGetId($matter_data);
            }

            DB::commit();

            return $m_id;

        }catch (\Exception $e){
            DB::rollBack();
            throw new \Exception($e->getMessage());
        }
    }

    //物料列表
    public function getMyPriceList($params)
    {
        $query = OAMatter::query();
        $list = $query->orderBy('id','DESC')
                ->where('supplier_id',$params['uid'])
                ->where('order_id',$params['order_id'])
                ->select(['type','money','add_time'])
                ->get()
                ->toArray();

        $supplier = OASupplier::query()->where('id',$params['uid'])->value('company');

        foreach ($list as $key =>  &$item){
            $item['index'] = $key + 1;
            $item['supplier'] = $supplier;
        }
        return $list;
    }


    //我的竞价结果
    public function getMyPriceResult($params)
    {
        $query = OAMatter::query();
        $uid = $params['uid'];
        $list = $query->where('order_id',$params['order_id'])
                      ->groupBy('supplier_id')
                      ->orderBy('money','ASC')
                      ->pluck('type','supplier_id')
//                        ->select(['money','supplier_id','type'])
//                        ->get()
                      ->toArray();
        $rank_id = array_search($params['uid'],array_keys($list));

        if($rank_id === false){
            return [];
        }else {
            $ret = [
                [
                    'index' => 1,
                    'rank_id' => $rank_id + 1,
                    'type' => $list[$uid],
                    'people_num' => count($list)
                ]
            ];
            return $ret;
        }
    }
}
